from flask import Flask,render_template,request,make_response
from werkzeug.utils import secure_filename
from paddleocr import PaddleOCR
from PIL import Image
import os
import json

ocr = PaddleOCR(use_angle_cls=False, use_gpu=False, lang='ch')

app = Flask(__name__)

@app.route('/', methods=['POST', 'GET'])
async def upload():
    if request.method == 'POST':
        f = request.files['file']
        if not (f.filename.split(".")[-1].upper() == "PNG" or f.filename.split(".")[-1].upper() == "JPG"):
            rsp = make_response(json.dumps({"msg": "文件格式有误，请上传JPG或PNG格式的图片！"}, ensure_ascii=False))
            rsp.headers['Content-Type']= 'application/json'
            return rsp
        basepath = os.path.dirname(__file__)  # 当前文件所在路径
        upload_path = os.path.join(basepath, 'static/uploads', secure_filename(f.filename))  #注意：没有的文件夹一定要先创建，不然会提示没有该路径
        f.save(upload_path)
        img_path = upload_path
        result = ocr.ocr(img_path, cls=False)
        image = Image.open(img_path).convert('RGB')
        boxes = [line[0] for line in result]
        txts = [line[1][0] for line in result]
        scores = [line[1][1] for line in result]
        res_data = [{"words": i, "scores": str(j)} for i, j in list(zip(txts, scores))]
        rsp = make_response(json.dumps({"data": res_data}, ensure_ascii=False))
        rsp.headers['Content-Type']= 'application/json'
        return rsp
    return render_template('upload.html')

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8080, debug=True)